package com.game.grid;


import javax.microedition.khronos.opengles.GL10;

import com.mcodesal.framework.ResourceProvider;
import com.mcodesal.framework.Sprite2D;
import com.mcodesal.framework.ResourceProvider.Texture;

import android.graphics.Point;

/**
 * This class controls the scrolling of the background grid.  This background
 * grid should scroll slower than the playable area to create a parallax effect.
 * It uses three sprites which which are recycled when they are no longer
 * visible.
 * 
 * @author Matias
 *
 */
public class GridManager {
	private Sprite2D grid1;
	private Sprite2D grid2;
	private Sprite2D grid3;
	private Point grid1Pos;
	private Point grid2Pos;
	private Point grid3Pos;
	private long lastTime = -1;
	
	public GridManager() {
		grid1 = new Sprite2D(320, 480);
		grid1.setTexture(ResourceProvider.getInstance().getTexture(Texture.BACKGROUND_GRID));
		grid2 = new Sprite2D(320, 480);
		grid2.setTexture(ResourceProvider.getInstance().getTexture(Texture.BACKGROUND_GRID));
		grid3 = new Sprite2D(320, 480);
		grid3.setTexture(ResourceProvider.getInstance().getTexture(Texture.BACKGROUND_GRID));
		grid1Pos = new Point(0, 0);
		grid2Pos = new Point(0, -480);
		grid3Pos = new Point(0, -960);
		
	}
	
	public void update(int speedMult, long gameTime) {
		if(lastTime == -1) {
			lastTime = gameTime;
		}
		if(gameTime-lastTime > 75) {
			grid1Pos.y = grid1Pos.y+2*speedMult;
			grid2Pos.y = grid2Pos.y+2*speedMult;
			grid3Pos.y = grid3Pos.y+2*speedMult;
			if(grid1Pos.y == 480) {
				grid1Pos.y = -960;
			}
			else if(grid2Pos.y == 480) {
				grid2Pos.y = -960;
			}
			else if(grid3Pos.y == 480) {
				grid3Pos.y = -960;
			}
			lastTime = gameTime;
		}
	}
	
	public void draw(GL10 gl){
		gl.glPushMatrix();
        gl.glTranslatef(grid1Pos.x, grid1Pos.y, 0);
		grid1.draw(gl);
		gl.glPopMatrix();
		
		gl.glPushMatrix();
        gl.glTranslatef(grid2Pos.x, grid2Pos.y, 0);
		grid2.draw(gl);
		gl.glPopMatrix();
		
		gl.glPushMatrix();
        gl.glTranslatef(grid3Pos.x, grid3Pos.y, 0);
		grid3.draw(gl);
		gl.glPopMatrix();
	}
}
